package com.concurrent.chapter1.concurrent01;

import java.util.concurrent.Semaphore;

//Semaphore的构造方法参数permits表示同一时间内
//最多允许多少个线程同时执行acquire()和release()之前的代码
public class Service {
	private Semaphore semaphore = new Semaphore(10);//一共有10个许可
	public void testMethod() {
		try {
			//System.out.println(Thread.currentThread().getName() + "进入testMethod方法 time:" + System.currentTimeMillis());
			semaphore.acquire(2);//每次执行消耗掉2个许可
			//System.out.println(Thread.currentThread().getName() + " begin time:" + System.currentTimeMillis());
			System.out.println(semaphore.getQueueLength() + "个线程正在等待");
			System.out.println("是否有线程正在等待semaphore：" + semaphore.hasQueuedThreads());
			System.out.println("可用许可个数" + semaphore.availablePermits());
			Thread.sleep(2000);
			//System.out.println(Thread.currentThread().getName() + " end time:" + System.currentTimeMillis());
			semaphore.release(2);
			System.out.println("可用许可个数" + semaphore.availablePermits());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

